package com.ctg.itrdc.k8sconsole.control;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ctg.itrdc.imageconsole.common.bean.CommonResult;
import com.ctg.itrdc.imageconsole.common.bean.ReturnCodeDefine;
import com.ctg.itrdc.imageconsole.data.dto.K8sRcDTO;
import com.ctg.itrdc.imageconsole.data.entity.K8sOperationRecord;
import com.ctg.itrdc.imageconsole.service.IK8sOperationRecordService;
import com.ctg.itrdc.k8sconsole.service.IRcService;
import com.ctg.itrdc.paspsdk.common.utils.json.JSONUtils;
import com.ctg.itrdc.paspsdk.common.utils.type.StringUtils;

/**
 * 
 * @description:
 * @version: v1.0.0
 * @author: Piao.Wu
 * 
 *          Modification History: Date Author Version Description
 *          -----------------------------------------------------------------
 *          2016年8月22日 上午9:56:09 Piao.Wu v1.0.0 create
 *
 */
@Controller
@RequestMapping("/rc")
public class RcController {

	@Resource
	private IRcService rcService;
	@Resource
	private IK8sOperationRecordService k8sOperationRecordService;

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	/**
	 * 
	 * @Description: 获取rc列表
	 * @author Piao.Wu 2016年9月7日 下午5:34:52
	 * @param clusterCode
	 * @param perpage
	 * @param page
	 * @param name
	 * @param namesp
	 * @return CommonResult
	 *
	 */
	@RequestMapping(value = "/queryRcs", method = RequestMethod.GET)
	@ResponseBody
	public CommonResult queryRcs(@RequestParam("clusterCode") String clusterCode,
			@RequestParam("perpage") String perpage, @RequestParam("page") String page,
			@RequestParam(value = "name", required = false) String name) {

		Map<String, Object> map = null;
		String jsonStr = null;
		for (int i = 0; i < 3; i++) {
			try {
				jsonStr = rcService.getRcs(clusterCode, perpage, page, name);
				map = JSONUtils.jsonToMap(jsonStr);
				break;
			} catch (Exception e) {
				logger.error("查询出错！", e);
				jsonStr = e.getLocalizedMessage();
			}
		}
		if (map == null || map.size() == 0) {
			return new CommonResult(ReturnCodeDefine.Code.C1101, jsonStr);
		}
		return new CommonResult(ReturnCodeDefine.Code.C1000, ReturnCodeDefine.Msg.M1000, map);
	}
	
	
	@RequestMapping(value = "/queryRcsByNamesp", method = RequestMethod.GET)
	@ResponseBody
	public CommonResult queryRcsByNamesp(@RequestParam("clusterCode") String clusterCode,
			@RequestParam("perpage") String perpage, @RequestParam("page") String page,
			@RequestParam(value = "name", required = false) String name,
			@RequestParam(value = "namesp", required = false) String namesp) {

		Map<String, Object> map = null;
		String jsonStr = null;
		for (int i = 0; i < 3; i++) {
			try {
				jsonStr = rcService.getRcsByNamesp(clusterCode, namesp, name, perpage, page);
				map = JSONUtils.jsonToMap(jsonStr);
				break;
			} catch (Exception e) {
				logger.error("查询出错！", e);
				jsonStr = e.getLocalizedMessage();
			}
		}
		if (map == null || map.size() == 0) {
			return new CommonResult(ReturnCodeDefine.Code.C1101, jsonStr);
		}
		return new CommonResult(ReturnCodeDefine.Code.C1000, ReturnCodeDefine.Msg.M1000, map);
	}
	

	/**
	 * 
	 * @Description: 获取rc详细信息
	 * @author Piao.Wu 2016年9月7日 下午5:35:08
	 * @param clusterCode
	 * @param name
	 * @param namesp
	 * @return CommonResult
	 *
	 */
	@RequestMapping(value = "/queryRcDetail", method = RequestMethod.GET)
	@ResponseBody
	public CommonResult queryRcDetail(@RequestParam("clusterCode") String clusterCode,
			@RequestParam("name") String name, @RequestParam("namesp") String namesp) {

		Map<String, Object> map = null;
		String jsonStr = null;
		for (int i = 0; i < 3; i++) {
			try {
				jsonStr = rcService.getRcDetail(clusterCode, name, namesp);
				map = JSONUtils.jsonToMap(jsonStr);
				break;
			} catch (Exception e) {
				logger.error("查询出错！", e);
				jsonStr = e.getLocalizedMessage();
			}
		}
		if (map == null || map.size() == 0) {
			return new CommonResult(ReturnCodeDefine.Code.C1101, jsonStr);
		}
		return new CommonResult(ReturnCodeDefine.Code.C1000, ReturnCodeDefine.Msg.M1000, map);
	}

	/**
	 * 
	 * @Description: rc扩缩容
	 * @author Piao.Wu 2016年9月7日 下午5:35:20
	 * @param rcDto
	 * @return CommonResult
	 *
	 */
	@RequestMapping(value = "/updateRcReplicas", method = RequestMethod.POST)
	@ResponseBody
	public CommonResult updateRcReplicas(@RequestBody K8sRcDTO rcDto) {

		Map<String, Object> map = null;
		String jsonStr = null;
		for (int i = 0; i < 3; i++) {
			try {
				jsonStr = rcService.updateRcReplicas(rcDto.getClusterCode(), rcDto.getName(), rcDto.getNamesp(),
						rcDto.getReplicas());
				map = JSONUtils.jsonToMap(jsonStr);
				break;
			} catch (Exception e) {
				logger.error("扩缩容时出异常！", e);
				jsonStr = e.getLocalizedMessage();
			}
		}
		if (map == null || map.size() == 0) {
			return new CommonResult(ReturnCodeDefine.Code.C1101, jsonStr);
		}
		return new CommonResult(ReturnCodeDefine.Code.C1000, ReturnCodeDefine.Msg.M1000, map);
	}
	
	@RequestMapping(value = "/delRc", method = RequestMethod.POST)
	@ResponseBody
	public CommonResult delRc(@RequestBody K8sRcDTO rcDto) {

		Map<String, Object> map = null;
		String jsonStr = null;
		for (int i = 0; i < 3; i++) {
			try {
				jsonStr = rcService.delRc(rcDto.getClusterCode(), rcDto.getNamesp(), rcDto.getName());
				map = JSONUtils.jsonToMap(jsonStr);
				break;
			} catch (Exception e) {
				logger.error("调用dashboard删除rc时出异常！", e);
				jsonStr = e.getLocalizedMessage();
			}
		}
		if (map == null || map.size() == 0) {
			return new CommonResult(ReturnCodeDefine.Code.C1101, jsonStr);
		}
		return new CommonResult(ReturnCodeDefine.Code.C1000, ReturnCodeDefine.Msg.M1000, map);
	}
	

	/**
	 * 
	 * @Description: rc扩缩容（开发者门户使用）
	 * @author Piao.Wu 2016年10月29日 上午10:45:52
	 * @param rcDto
	 * @return CommonResult
	 *
	 */
	@RequestMapping(value = "/expandOrNarrowRc", method = RequestMethod.POST)
	@ResponseBody
	public CommonResult expandOrNarrowRc(@RequestBody K8sRcDTO rcDto) {
		try {
			Long recordId = rcService.expandOrNarrowRc(rcDto.getK8sUrl(), rcDto.getNamesp(), rcDto.getName(),
					rcDto.getReplicas());
			if (recordId!=null) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("recordId", recordId);
				return new CommonResult(ReturnCodeDefine.Code.C1000, ReturnCodeDefine.Msg.M1000,map);
			}
			return new CommonResult(ReturnCodeDefine.Code.C1200, "rc扩缩容出现异常！");
		} catch (Exception e) {
			logger.error("rc扩缩容出现异常！", e);
			return new CommonResult(ReturnCodeDefine.Code.C1200, e.getMessage());
		}
	}

	/**
	 * 
	 * @Description: rc重启（开发者门户使用）
	 * @author Piao.Wu 2016年10月29日 上午10:21:23
	 * @param rcDto
	 * @return CommonResult
	 *
	 */
	@RequestMapping(value = "/restartRc", method = RequestMethod.POST)
	@ResponseBody
	public CommonResult restartRc(@RequestBody K8sRcDTO rcDto) {
		try {
			Long recordId = rcService.restartRc(rcDto.getK8sUrl(), rcDto.getNamesp(), rcDto.getName());
			if (recordId!=null) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("recordId", recordId);
				return new CommonResult(ReturnCodeDefine.Code.C1000, ReturnCodeDefine.Msg.M1000,map);
			}
			return new CommonResult(ReturnCodeDefine.Code.C1200, "重启rc异常！");
		} catch (Exception e) {
			logger.error("重启rc异常！", e);
			return new CommonResult(ReturnCodeDefine.Code.C1200, e.getMessage());
		}
	}

	/**
	 * 
	 * @Description: rc删除（开发者门户使用）
	 * @author Piao.Wu 2016年10月29日 上午10:21:37
	 * @param rcDto
	 * @return CommonResult
	 *
	 */
	@RequestMapping(value = "/deleteRc", method = RequestMethod.POST)
	@ResponseBody
	public CommonResult deleteRc(@RequestBody K8sRcDTO rcDto) {
		try {
			Long recordId = rcService.deleteRc(rcDto.getK8sUrl(), rcDto.getNamesp(), rcDto.getName());
			if (recordId!=null) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("recordId", recordId);
				return new CommonResult(ReturnCodeDefine.Code.C1000, ReturnCodeDefine.Msg.M1000,map);
			}
			return new CommonResult(ReturnCodeDefine.Code.C1200, "删除rc异常！");
		} catch (Exception e) {
			logger.error("删除rc异常！", e);
			return new CommonResult(ReturnCodeDefine.Code.C1200, e.getMessage());
		}
	}

	/**
	 * 
	 * @Description: 查询执行情况，例如可根据此接口 判断rc删除、重启、扩缩容是否成功
	 * @author Piao.Wu 2016年11月8日 下午5:00:43
	 * @param k8sUrl
	 * @param namesp
	 * @param rcId
	 * @return
	 * CommonResult
	 *
	 */
	@RequestMapping(value = "/queryExecuteInfo", method = RequestMethod.GET)
	@ResponseBody
	public CommonResult queryExecuteInfo(@RequestParam(value = "k8sUrl", required = false) String k8sUrl,
			@RequestParam(value = "namesp", required = false) String namesp, @RequestParam(value = "recordId") Long recordId) {
		try {
			K8sOperationRecord record = new K8sOperationRecord();
			record.setId(recordId);
			if (StringUtils.isNotEmpty(k8sUrl)) {
				record.setK8sUrl(k8sUrl);
			}
			if (StringUtils.isNotEmpty(namesp)) {
				record.setNamespace(namesp);
			}
			record = k8sOperationRecordService.queryByK8sOperationRecord(record);
			return new CommonResult(ReturnCodeDefine.Code.C1000, ReturnCodeDefine.Msg.M1000, record);
		} catch (Exception e) {
			logger.error("查询执行状态时出现异常！", e);
			return new CommonResult(ReturnCodeDefine.Code.C1200, e.getMessage());
		}
	}

}
